#!/usr/bin/env python3
import requests
import json
import re
from datetime import datetime

def trace_template_data():
    """追踪模板数据的来源"""
    base_url = "http://127.0.0.1:5000"
    
    print("=== 追踪模板数据来源 ===")
    print(f"时间: {datetime.now()}")
    
    try:
        # 1. 发送POST请求并获取完整响应
        print("\n1. 发送POST请求...")
        response = requests.post(base_url, data={'coin': 'BTC'})
        html_content = response.text
        
        print(f"响应状态码: {response.status_code}")
        print(f"响应大小: {len(html_content)} 字符")
        
        # 2. 分析HTML结构，查找数据来源
        print("\n2. 分析HTML结构...")
        
        # 查找所有包含已移除指标的行
        removed_indicators = {
            'stochastic k': '22.88',
            'williams %r': '-77.12', 
            'cci': '-48.71',
            'momentum': '98.31'
        }
        
        lines = html_content.split('\n')
        problem_lines = []
        
        for i, line in enumerate(lines):
            line_lower = line.lower()
            for indicator, value in removed_indicators.items():
                if indicator in line_lower or value in line:
                    problem_lines.append({
                        'line_num': i + 1,
                        'content': line.strip(),
                        'indicator': indicator,
                        'value': value
                    })
        
        print(f"发现 {len(problem_lines)} 个问题行")
        
        # 3. 分析问题行的上下文
        print("\n3. 分析问题行上下文...")
        
        for item in problem_lines:
            line_num = item['line_num']
            print(f"\n--- 第{line_num}行 ---")
            print(f"内容: {item['content']}")
            
            # 显示前后10行的上下文
            start = max(0, line_num - 11)
            end = min(len(lines), line_num + 10)
            
            print("上下文:")
            for j in range(start, end):
                marker = ">>> " if j == line_num - 1 else "    "
                print(f"{marker}{j+1:3d}: {lines[j]}")
        
        # 4. 查找可能的数据注入点
        print("\n4. 查找数据注入点...")
        
        # 查找Jinja2模板变量
        template_vars = re.findall(r'\{\{\s*([^}]+)\s*\}\}', html_content)
        print(f"发现 {len(template_vars)} 个模板变量")
        
        # 查找包含技术分析数据的变量
        tech_vars = [var for var in template_vars if 'technical' in var.lower()]
        if tech_vars:
            print("技术分析相关变量:")
            for var in tech_vars[:10]:  # 只显示前10个
                print(f"  - {var}")
        
        # 5. 查找JavaScript数据
        print("\n5. 查找JavaScript数据...")
        
        script_pattern = r'<script[^>]*>(.*?)</script>'
        scripts = re.findall(script_pattern, html_content, re.DOTALL | re.IGNORECASE)
        
        js_data_found = False
        for i, script in enumerate(scripts):
            script_lower = script.lower()
            for indicator, value in removed_indicators.items():
                if indicator.replace(' ', '_') in script_lower or value in script:
                    print(f"脚本 {i+1} 中发现数据:")
                    print(f"  指标: {indicator}, 值: {value}")
                    # 显示相关的脚本片段
                    lines_in_script = script.split('\n')
                    for j, script_line in enumerate(lines_in_script):
                        if indicator.replace(' ', '_') in script_line.lower() or value in script_line:
                            print(f"    第{j+1}行: {script_line.strip()}")
                    js_data_found = True
        
        if not js_data_found:
            print("JavaScript中未发现已移除指标数据")
        
        # 6. 查找内联JSON数据
        print("\n6. 查找内联JSON数据...")
        
        json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
        json_matches = re.findall(json_pattern, html_content)
        
        json_data_found = False
        for j, json_str in enumerate(json_matches):
            json_lower = json_str.lower()
            for indicator, value in removed_indicators.items():
                if indicator.replace(' ', '_') in json_lower or value in json_str:
                    print(f"JSON数据 {j+1} 中发现:")
                    print(f"  指标: {indicator}, 值: {value}")
                    print(f"  JSON: {json_str[:200]}...")
                    json_data_found = True
        
        if not json_data_found:
            print("内联JSON中未发现已移除指标数据")
        
        # 7. 检查是否有硬编码的HTML
        print("\n7. 检查硬编码HTML...")
        
        # 查找包含这些值的HTML标签
        for indicator, value in removed_indicators.items():
            # 查找包含指标名称的标签
            name_pattern = rf'<[^>]*{re.escape(indicator)}[^>]*>'
            name_matches = re.findall(name_pattern, html_content, re.IGNORECASE)
            
            # 查找包含指标值的标签
            value_pattern = rf'<[^>]*{re.escape(value)}[^>]*>'
            value_matches = re.findall(value_pattern, html_content)
            
            if name_matches or value_matches:
                print(f"\n指标 {indicator} (值: {value}):")
                if name_matches:
                    print(f"  名称匹配: {len(name_matches)} 个")
                    for match in name_matches[:3]:  # 只显示前3个
                        print(f"    {match}")
                if value_matches:
                    print(f"  值匹配: {len(value_matches)} 个")
                    for match in value_matches[:3]:  # 只显示前3个
                        print(f"    {match}")
        
        # 8. 总结分析结果
        print("\n8. 分析总结")
        print("=" * 50)
        
        if problem_lines:
            print(f"❌ 发现 {len(problem_lines)} 个包含已移除指标的行")
            print("这些指标数据可能来源于:")
            print("  1. 硬编码的HTML模板")
            print("  2. 缓存的模板数据")
            print("  3. JavaScript中的静态数据")
            print("  4. 服务器端的默认/测试数据")
            
            print("\n建议检查:")
            print("  - 模板文件是否有未提交的更改")
            print("  - 是否有模板缓存需要清理")
            print("  - 服务器是否需要重启")
            print("  - 是否有其他模板文件包含这些数据")
        else:
            print("✅ 未发现已移除指标的数据")
    
    except Exception as e:
        print(f"追踪过程中出错: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    trace_template_data()